package com.mjr.webmanage.aop;


import com.mjr.webmanage.mapper.OperateLogMapper;
import com.mjr.webmanage.pojo.OperateLog;
import com.mjr.webmanage.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 操作日志切面
 */
@Slf4j
@Component
@Aspect
public class OperateLogAspect {


    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(com.mjr.webmanage.anno.Log)")
    public Object recordOperateLog(ProceedingJoinPoint pjp) throws Throwable {
        OperateLog operateLog = new OperateLog();
        String jwt = request.getHeader("Token");
        Claims claims = JwtUtils.parseJWT(jwt);
        Integer empId = (Integer) claims.get("id");

        operateLog.setOperateEmpId(empId);
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(pjp.getTarget().getClass().getName());
        operateLog.setMethodName(pjp.getSignature().getName());
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));

        long begin = System.currentTimeMillis();

        Object proceed = pjp.proceed();

        long end = System.currentTimeMillis();

        operateLog.setCostTime(end - begin);
        operateLog.setReturnValue(proceed.toString());

        operateLogMapper.insert(operateLog);
        return proceed;
    }

}
